<template>
  <div class="app-container">
    <el-form :model="queryParams.condition" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      label-width="auto">
      <el-form-item label="检测开始日期" prop="checkDate">
        <el-date-picker clearable v-model="queryParams.condition.checkDate" value-format="yyyy-MM-dd" type="daterange"
          range-separator="到" start-placeholder="请选择开始日期" end-placeholder="请选择结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="SN码（序列号）" prop="snCode">
        <el-input v-model="queryParams.condition.snCode" placeholder="请输入SN码（序列号）" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产线" prop="lineIds">
        <el-select v-model="queryParams.condition.lineIds" placeholder="请选择产线" clearable style="width: 100%">
          <el-option v-for="dict in lineList" :key="dict.lineId" :label="dict.lineName" :value="dict.lineId" />
        </el-select>
      </el-form-item>
      <el-form-item label="工单编号" prop="workorderCode">
        <el-input v-model="queryParams.condition.workorderCode" placeholder="请输入工单编号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName" style="margin-right: 94px">
        <el-input v-model="queryParams.condition.productName" placeholder="请输入产品名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品规格" prop="productSpc">
        <el-input v-model="queryParams.condition.productSpc" placeholder="请输入产品规格" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户" prop="remark">
        <el-input v-model="queryParams.condition.remark" placeholder="请输入客户" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="合同号" prop="fText4">
        <el-input v-model="queryParams.condition.fText4" placeholder="请输入合同号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['qc:pcba:check:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <download-excel class="export-btn" :fetch="fetchData" :fields="jsonFields" type="xlsx" header="PCBA首末件列表"
          name="PCBA首末件列表.xlsx">
          <el-button type="warning" icon="el-icon-download" size="mini"
            v-hasPermi="['qc:pcba:check:export']">导出</el-button>
        </download-excel>
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="qcindexList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column type="index" label="序号" align="center" width="50" />
      <!-- <el-table-column label="检验编号" align="center" prop="id"> 
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">{{scope.row.id}}</el-button>
        </template>
</el-table-column>-->
      <!-- <el-table-column label="型号" align="center" prop="productSpc"></el-table-column> -->
      <el-table-column label="序列号" align="center" prop="snCode">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">{{
            scope.row.snCode
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="产线" align="center" prop="lineName" />
      <el-table-column label="工单编号" align="center" prop="workorderCode" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品规格" align="center" prop="productSpc" />
      <el-table-column label="客户" align="center" prop="custName" />
      <el-table-column label="合同号" align="center" prop="ftext4" />
      <el-table-column label="外观检验" align="center" prop="APPEARANCE">
        <template slot-scope="scope">{{
          scope.row.APPEARANCE == "0"
            ? "×"
            : scope.row.APPEARANCE == "1"
              ? "√"
              : "--"
        }}</template>
      </el-table-column>

      <el-table-column label="测试" align="center" prop="TEST">
        <template slot-scope="scope">{{
          scope.row.TEST == "0" ? "×" : scope.row.TEST == "1" ? "√" : "--"
        }}</template>
      </el-table-column>
      <el-table-column label="老化" align="center" prop="BURN IN">
        <template slot-scope="scope">{{
          scope.row["BURN IN"] == "0"
            ? "×"
            : scope.row["BURN IN"] == "1"
              ? "√"
              : "--"
        }}</template>
      </el-table-column>
      <el-table-column label="三防点胶" align="center" prop="THREE ANTIDISPENSING">
        <template slot-scope="scope">{{
          scope.row["THREE ANTIDISPENSING"] == "0"
            ? "×"
            : scope.row["THREE ANTIDISPENSING"] == "1"
              ? "√"
              : "--"
        }}</template>
      </el-table-column>

      <el-table-column label="检验结果" align="center" prop="checkResult">
        <template slot-scope="scope">{{
          scope.row.checkResult == "0"
            ? "×"
            : scope.row.checkResult == "1"
              ? "√"
              : "--"
        }}</template>
      </el-table-column>
      <!-- <el-table-column label="检验员" align="center" prop="checkResult"></el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['qc:pcba:check:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['qc:pcba:check:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
      @pagination="getList" />

    <!-- 添加或修改检测项对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body @close="cancel">
      <div class="dialogContent">
        <el-form ref="form" :model="form" :rules="rules" label-width="140px">
          <!-- <el-row>
            <el-col :span="12">
              <el-form-item label="类型" prop="headEndCheckType">
                <el-radio-group
                  v-model="form.headEndCheckType"
                  :disabled="optType=='add'? false:true"
                >
                  <el-radio label="FIRST">首件</el-radio>
                  <el-radio label="FINAL">末件</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>-->
          <el-row style="padding-left: 14px; margin-bottom: 14px"><el-button type="warning" icon="el-icon-download"
              @click="handleDetailExport" v-if="optType == 'view'">导出</el-button></el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="SN码(序列号)" prop="snCode">
                <el-input id="scanner-input5" v-model="form.snCode" placeholder
                  :disabled="optType == 'add' ? false : true" @input="snbutton" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="工单编号:" prop="workorderCode">
                <el-input v-model="form.workorderCode" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="型号" prop="productSpc">
                <el-input v-model="form.productSpc" placeholder :disabled="optType == 'add' ? false : true" />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="首件时间" prop="productSpc">
                <el-input v-model="form.productSpc" placeholder :disabled="optType=='add'? false:true" />
              </el-form-item>
            </el-col>-->
          </el-row>
          <el-row>
            <el-table v-loading="loading1" :data="templateList" :span-method="objectSpanMethod">
              <el-table-column label="类型" align="center" prop="indexType" width="120">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.mes_index_type" :value="scope.row.indexType" />
                </template>
              </el-table-column>
              <el-table-column type="index" width="50"></el-table-column>
              <el-table-column label="检测项目" align="center" prop="indexName" class-name="tableLi" />
              <el-table-column label="检测依据" align="center" prop="indexType" width="110">
                <template slot-scope="scope">
                  <div>PCBA调试作业指导书，三防点胶规范</div>
                </template>
              </el-table-column>
              <el-table-column label="检验结果" align="center" prop="checkResult" width="240">
                <template slot-scope="scope">
                  <!-- <el-form-item label="" prop="checkResult" class="tableItem"> -->
                  <div v-if="optType == 'add' || optType == 'edit'">
                    <el-radio-group v-model="scope.row.checkResult" @input="checkChange"
                      v-if="judegShow(scope.row.attr1)">
                      <el-radio :label="1" value="1">√</el-radio>
                      <el-radio :label="0" value="0">×</el-radio>
                    </el-radio-group>

                    <!-- {{ scope.row.attr1 && JSON.parse(scope.row.attr1) }} -->
                    <!-- judegShowInput(scope.row.attr1,scope.$index) -->
                    <ul v-if="scope.row.attrObj.type == '1'">
                      <li v-for="(item, i) in scope.row.resultList" :key="i" class="mInput">
                        <span>M</span>
                        <el-input v-model="item.id" style="width: 70px" @input="(e) => inputCheckout(e, scope.row, scope.$index, i)
                          " />
                        <el-input v-model="item.num" style="width: 70px" @input="(e) => inputCheckout(e, scope.row, scope.$index, i)
                          " />
                        <i class="el-icon-circle-plus-outline" @click="mInputAdd(scope.row, scope.$index, i)"></i>
                        <i v-if="i != 0" class="el-icon-remove-outline"
                          @click="mInputDel(scope.row, scope.$index, i)"></i>
                      </li>
                    </ul>
                  </div>

                  <div v-if="optType == 'view'">
                    <div>
                      {{
                        scope.row.checkResult == "0"
                          ? "×"
                          : scope.row.checkResult == "1"
                            ? "√"
                            : "--"
                      }}
                    </div>
                    <div v-if="scope.row.attrObj.type == '1'">
                      <div v-for="(item, i) in scope.row.resultList" :key="i" class="mInput">
                        <span>M</span>
                        <span>{{ item.id }}：</span>
                        <span>{{ item.num }}</span>
                      </div>
                    </div>
                  </div>

                  <!-- </el-form-item> -->
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="说明:">
                <div>
                  在主要元器件与产品特性对应处核对并记录数据等信息，在检验项目检验结果项符合项打“√”不符合项打“×”，不合格品按《不合格品管理规定》处理。
                  <br />螺钉紧固标准：
                  <br />
                  <span>
                    M3：0.5～0.7N.M
                    <span style="margin-left: 30px">M4：0.8～1.0N.M</span>
                  </span>
                  <span>
                    <br />M5：1.1～1.3N.M
                    <span style="margin-left: 30px">M6：1.6～1.8N.M</span>
                  </span>
                  <br />
                  <span>M8：10±1 N.M</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="imgDiv">
              <el-form-item label="检验结果" prop="checkResult">
                <el-radio-group v-model="form.checkResult" disabled>
                  <el-radio :label="1">√</el-radio>
                  <el-radio :label="0">×</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注:" prop="remark">
                <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"
                  :autosize="{ minRows: 2, maxRows: 5 }" style="width: 450px; height: 100px" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="this.form.checkResult === 0">
            <el-col :span="24" class="imgDiv">
              <el-form-item label="不合格品处理方式" prop="repairState">
                <el-radio-group v-model="form.repairState">
                  <el-radio label="1">返工</el-radio>
                  <el-radio label="2">返修</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="this.form.checkResult === 0">
            <el-col :span="24">
              <el-form-item label="异常记录">
                <el-table :data="errorList">
                  <el-table-column label="类型选择" align="center" prop="indexType">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.indexType" placeholder="请选择检测项类型" clearable>
                        <el-option v-for="dict in errorTypeList" :key="dict.indexType" :label="dict.indexTypeName"
                          :value="dict.indexType" />
                      </el-select>
                    </template>
                  </el-table-column>

                  <el-table-column label="异常描述" align="center" prop="describeData">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.describeData" placeholder type="textarea" />
                    </template>
                  </el-table-column>
                  <el-table-column label="文件上传" align="center" prop="fileName">
                    <template slot-scope="scope">
                      <ImageUpload :limit="1" :value="scope.row.fileName" :fileSize="15"
                        @input="(url) => handleImgUplaoded(url, scope.$index)" @onRemoved="handleImgRemoved">
                      </ImageUpload>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button size="medium" type="text" icon="el-icon-circle-plus-outline"
                        @click="errorAdd"></el-button>
                      <el-button v-if="scope.$index != 0" size="medium" type="text" icon="el-icon-remove-outline"
                        @click="errorDel(scope.$index)"></el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType == 'view'">返回</el-button>
        <el-button type="primary" @click="submitForm" v-else>确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInspection,
  getInspection,
  delInspection,
  addInspection,
  updateInspection,
  templateindexList,
  listError,
  firstcheckSncode,
  getExportDataList,
} from "@/api/mes/qc/dcCharging";
import ImageUpload from "@/components/ImageUpload/index.vue";
import { productionlineList } from "@/api/mes/qc/qcipqc";
import JsonExcel from "vue-json-excel";
export default {
  name: "PcbaCheckout",
  dicts: ["mes_index_type", "mes_product_type"],
  components: { ImageUpload, DownloadExcel: JsonExcel },
  data() {
    return {
      jsonFields: {
        序列号: "snCode",
        产线: "lineName",
        工单编号: "workorderCode",
        产品名称: "productName",
        产品规格: "productSpc",
        客户: "custName",
        合同号: "ftext4",
        外观检验: {
          field: "inspectionLineMap.APPEARANCE",
          callback: (value) => {
            return value == "0" ? "×" : value == "1" ? "√" : "--";
          },
        },
        测试: {
          field: "inspectionLineMap.TEST",
          callback: (value) => {
            return value == "0" ? "×" : value == "1" ? "√" : "--";
          },
        },
        老化: {
          field: "inspectionLineMap.BURN IN",
          callback: (value) => {
            return value == "0" ? "×" : value == "1" ? "√" : "--";
          },
        },
        三方点胶: {
          field: "inspectionLineMap.THREE ANTIDISPENSING",
          callback: (value) => {
            return value == "0" ? "×" : value == "1" ? "√" : "--";
          },
        },

        检验结果: {
          field: "checkResult",
          callback: (value) => {
            return value == "0" ? "×" : value == "1" ? "√" : "--";
          },
        },
      },

      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检测项表格数据
      qcindexList: [],
      qcDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        rows: 10,
        condition: {
          snCode: null,
          indexName: null,
          indexType: null,
          qcTool: null,
          checkDate: null,
        }

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        snCode: [
          {
            required: true,
            message: "SN码（序列号）不能为空",
            trigger: "blur",
          },
        ],
        checkResult: [
          { required: true, message: "检验结果不能为空", trigger: "change" },
        ],
        checkResult1: [
          { required: true, message: "检验结果不能为空", trigger: "change" },
        ],
        // headEndCheckType: [
        //   { required: true, message: "类型不能为空", trigger: "change" }
        // ]
      },
      indexCodeDisabled: false,
      // 模板列表
      templateList: [],
      loading1: false,
      spanArr: [],
      //  异常记录列表
      errorList: [{}],
      errorTypeList: [],
      templateId: "18",
      productType: "PCBA",
      lineList: [],
    };
  },
  created() {
    this.getlineList();
    this.getList();
  },
  methods: {
    handleDetailExport() {
      const id = this.form.id;
      this.download(
        "/mes/firstlast/inspection/detail/export/" + id,
        {
          ...this.queryParams,
        },
        `PCBA首末件检验详情.xlsx`,
        {},
        "get"
      );
    },
    //获取产线列表
    getlineList() {
      productionlineList().then((res) => {
        if (res.code == 200) {
          this.lineList = res.data;
        }
      });
    },
    /** 查询检测项列表 */
    getList() {
      this.loading = true;
      this.queryParams.condition.productType = "PCBA";
      const query = { ...this.queryParams };
      if (this.queryParams.condition.checkDate) {
        query.condition.checkStartDate = this.queryParams.condition.checkDate[0] + " 00:00:00";
        query.condition.checkEndDate = this.queryParams.condition.checkDate[1] + " 23:59:59";
      }
      else {
        query.condition.checkStartDate = null;
        query.condition.checkEndDate = null;
      }
      listInspection(query).then((response) => {
        let list = [];
        for (let i = 0; i < response.data.datas.length; i++) {
          // let obj= response.rows[i].inspectionLineMap;
          let obj = {
            ...response.data.datas[i],
            ...response.data.datas[i].inspectionLineMap,
          };
          list.push(obj);
        }
        this.qcindexList = list;
        this.total = response.data.total;
        console.log(this.qcindexList, "======list======");
        this.loading = false;
      });
    },
    getErrorlist() {
      let params = {};
      params.productType = this.productType;
      params.templateId = this.templateId;
      listError(params).then((response) => {
        this.errorTypeList = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        checkResult: null,
        snCode: null,
        indexName: null,
        indexType: null,
        headEndCheckType: null,
        remark: null,
        repairState: null,
      };
      this.templateList = [];
      this.autoGenFlag = false;
      this.loading1 = false;
      this.errorList = [{}];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      console.log(this.queryParams.condition, "=====queryParams.condition===");
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.condition.checkDate = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.indexId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      this.indexCodeDisabled = false;
      this.open = true;
      this.title = "新增PCBA首末件检验";
      this.optType = "add";
      this.templatePost();
      this.getErrorlist();
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      const id = row.id;
      this.getErrorlist();
      getInspection(id).then((response) => {
        let qcobj = response.data?.qcInspectionResult || {};
        this.form = { ...qcobj, ...response.data };
        this.errorList = response.data?.qcInspectionResult
          ?.exceptionLogList || [{}];
        let list = [];
        for (let i = 0; i < response.data.itemList.length; i++) {
          let obj = response.data.itemList[i];
          let attrList = response.data.itemList[i].attr2;
          obj.resultList = JSON.parse(attrList);
          obj.attrObj = obj.attr1 ? JSON.parse(obj.attr1) : { type: "0" };
          list.push(obj);
        }
        this.templateList = list || [];
        this.open = true;
        this.title = "查看PCBA首末件检验";
        this.optType = "view";
        this.getSpanArr(response.data.itemList || []);
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.indexCodeDisabled = true;
      const id = row.id;
      this.getErrorlist();
      getInspection(id).then((response) => {
        this.open = true;
        let qcobj = response.data?.qcInspectionResult || {};
        this.form = { ...qcobj, ...response.data };
        this.form.id = response.data.id;
        this.errorList = response.data?.qcInspectionResult
          ?.exceptionLogList || [{}];
        let list = [];
        for (let i = 0; i < response.data.itemList.length; i++) {
          let obj = response.data.itemList[i];
          let attrList = response.data.itemList[i].attr2;
          obj.resultList = JSON.parse(attrList);
          obj.attrObj = obj.attr1 ? JSON.parse(obj.attr1) : { type: "0" };
          list.push(obj);
        }
        this.templateList = list;
        this.title = "修改PCBA首末件检验";
        this.optType = "edit";
        this.getSpanArr(list || []);
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.templateList, "=====templateList===");
      let bool = false;
      for (let i = 0; i < this.templateList.length; i++) {
        const element = this.templateList[i].checkResult;
        this.templateList[i].attr2 = JSON.stringify(
          this.templateList[i].resultList
        );
        console.log(element);
        if (element === undefined) {
          bool = true;
        }
      }
      if (bool) {
        this.$message({
          message: "请填写检验结果！！！",
          type: "warning",
        });
        return;
      }
      this.$refs["form"].validate((valid, value) => {
        console.log(valid, value, "===valid===");

        let params = { ...this.form };
        if (this.form.checkResult === 0) {
          params.qcInspectionResult = {
            snCode: this.form.snCode,
            productType: this.productType,
            exceptionLogList: this.errorList,
            inspectionType: "1",
            checkResult: this.form.checkResult,
            repairState: this.form.repairState,
          };
        }
        params.itemList = this.templateList;
        params.productType = this.productType;
        params.templateId = this.templateId;
        if (valid) {
          if (this.form.id != null) {
            updateInspection(params).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          } else {
            addInspection(params).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          }
        } else {
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm('是否确认删除检测编号为"' + id + '"的数据项？')
        .then(function () {
          return delInspection(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    // 获取新增表格列表
    templatePost() {
      this.loading1 = true;
      let params = {
        pageNum: 1,
        pageSize: 999999,
        templateId: this.templateId,
      };
      templateindexList(params).then((response) => {
        // this.templateList = response.rows;
        let list = [];
        response.rows.map((item, index) => {
          list.push(
            Object.assign({}, item, {
              resultList: [{ id: "", num: "" }],
              attrObj: item.attr1 ? JSON.parse(item.attr1) : { type: "0" },
            })
          );
        });
        this.templateList = list;
        this.getSpanArr(list);
        console.log(this.templateList, "=======list=======");
        this.loading1 = false;
      });
    },

    headFirst({ row, colunm, rowIndex, columnIndex }) {
      if (rowIndex === 1) {
        //这里为了是将第二列的表头隐藏，就形成了合并表头的效果
        return { display: "none" };
      }
      return "background:#f5f7fa";
    },
    // 行合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 3) {
        let index = this.templateList.length;
        if (rowIndex % index === 0) {
          return {
            rowspan: index,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }

      if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex]; // 合并行数
        const _col = this.spanArr[rowIndex] > 0 ? 1 : 0; // 合并的列数
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },

    getSpanArr(data) {
      this.spanArr = []; // tip: 后台获取完成数据后，一定要重置spanArr=[],避免出现合并混乱！！！！！
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          // 当为第一行时
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
          } else {
            // 判断当前值是否与上一行的【名称】相等，相等则进行合并
            if (data[i].indexType === data[i - 1].indexType) {
              this.spanArr[this.pos] += 1; // 合并单元格：合并的行数 +1
              this.spanArr.push(0); // 0代表单元格是不需要显示, 已经被合并的单元格
            } else {
              this.spanArr.push(1); // 1代表当前这行的数据需要被显示
              this.pos = i;
            }
          }
        }
      }
    },
    // 判断当前是否是合格
    checkChange(value) {
      let bool = this.templateList.every(({ checkResult }) => checkResult == 1);
      this.form.checkResult = bool ? 1 : 0;
    },
    //图片上传成功
    handleImgUplaoded(imgUrl, i) {
      console.log(imgUrl, i, "=========");
      this.errorList[i].fileName = imgUrl;
      // this.form.sopUrl = imgUrl;
    },
    //图片移除
    handleImgRemoved(imgUrl) {
      console.log(imgUrl);
      this.form.sopUrl = null;
    },
    // 异常记录增加
    errorAdd() {
      let obj = {};
      this.errorList.push(obj);
    },
    // 删除异常记录
    errorDel(index) {
      this.errorList.splice(index, 1);
    },
    // 判断是否是M几
    judegShowInput(attr, index) {
      let obj = {};
      if (attr) {
        obj = JSON.parse(attr);
      }
      if (obj.type == "1") {
        return true;
      } else {
        return false;
      }
    },

    //sn扫码函数
    snbutton(e) {
      var myInputOrder = document.getElementById("scanner-input5");
      myInputOrder.onkeydown = (even) => {
        console.log(even, "=====even5=====");
        if (even.key == "Enter") {
          let params = {
            snCode: e,
          };
          firstcheckSncode(params).then((res) => {
            console.log(res, "sn查询的res");
            if (res.code == 200) {
              this.$set(this.form, "workorderCode", res.data.workorderCode);
            }
          });
        }
      };
    },

    // 判断是否显示打钩单选
    judegShow(attr) {
      return true;
    },
    mInputAdd(row, index) {
      let obj = { id: "", num: "" };
      let obj1 = { ...this.templateList[index] };
      obj1.resultList.push(obj);
      // this.templateList[index].resultList.push(obj);
      this.$set(this.templateList, index, obj1);
      console.log(this.templateList, "======");
    },
    mInputDel(row, index, i) {
      this.templateList[index].resultList.splice(i, 1);
    },
    // 判断是否合格 （M几的）
    inputCheckout(e, row, index, i) {
      let a = row.resultList[i].id;
      let num = row.resultList[i].num;
      let list = row.attrObj.list;
      let min = "";
      let max = "";
      let obj = list.filter((item) => item.id == a);
      if (obj.length > 0) {
        min = obj[0].min;
        max = obj[0].max;
      }
      if (num >= min && num <= max) {
        console.log(true, "=====");
        this.templateList[index].checkResult = 1;
      } else {
        this.templateList[index].checkResult = 0;
      }

      let obj1 = { ...this.templateList[index] };
      this.$set(this.templateList, index, obj1);
      this.checkChange();
    },
    async fetchData() {
      this.loading = true;
      let data = [];
      this.queryParams.condition.productType = "PCBA";
      const query = { ...this.queryParams.condition };
      if (this.queryParams.condition.checkDate) {
        query.checkStartDate =
          this.queryParams.condition.checkDate[0] + " 00:00:00";
        query.checkEndDate =
          this.queryParams.condition.checkDate[1] + " 23:59:59";
      } else {
        query.checkStartDate = null;
        query.checkEndDate = null;
      }
      const res = await getExportDataList(query);
      if (res.code = 200) {
        data = res.data;
        this.loading = false;
      }
      return data;
    },
  },
};
</script>
<style scoped>
.tableItem .el-form-item__content {
  margin-left: 0px !important;
}

.tableItem ::v-deep .el-form-item__content {
  margin-left: 0px !important;
}

.dialogContent ::v-deep .el-upload--picture-card {
  width: 80px;
  height: 80px;
  line-height: 80px;
}

.dialogContent .el-table {
  font-size: 12px;
}

ul li {
  list-style: none;
}

.mInput {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.el-icon-circle-plus-outline {
  font-size: 16px;
}

.el-icon-remove-outline {
  font-size: 16px;
}
</style>
